# -*- coding: utf-8 -*-
import sys
import logging
import sqlalchemy
from lxml import etree
from pylons import config
from xadmin.model import *
from xadmin.lib.base import *

log = logging.getLogger(__name__)

class ClientrequirementsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('clientrequirement', 'clientrequirements')

    def index(self, format='html'):
        """GET /clientrequirements: All items in the collection."""
        # url_for('clientrequirements')
        c.requirements_url = self._getAbsoluteURL(h.url_for('clientrequirements'))
        c.server = config['server.url']
        c.requirements = Session.query(ClientRequirement).all()
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/clientrequirements/list.mako')

    def listByProject(self, project):
        """GET /:project/clientrequirements: All Client Requirements in a project."""
        # url_for('clientrequirements_by_project')
        project = Session.query(Project).get(project)
        if project is not None:
            c.requirements_url = self._getAbsoluteURL(h.url_for('clientrequirements'))
            c.server = config['server.url']
            c.requirements = Session.query(ClientRequirement).filter_by(project_id=project.id).all()
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/clientrequirements/list.mako')
        else:
            abort(404)

    def create(self):
        """POST /clientrequirements: Create a new item."""
        # url_for('clientrequirements')
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            tree = etree.fromstring(content)
            project_id = doc.xpath('/requirement/project')[0].text
            self._createClientRequirement(project_id, content)
            del response.headers['Content-Type']
            response.headers['Location'] = self._getAbsoluteURL(h.url_for('clientrequirement', id=cr.id))
            response.status_code = 201
            return
        except etree.XMLSyntaxError:
            abort(400)

    def createByProject(self, project):
        """POST /:project/clientrequirements: Create a new Client Requirement to a project."""
        # url_for('create_clientrequirements_by_project')
        try:
            project = Session.query(Project).get(project)
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            if not content:
                content = request.params.get('xml')
            cr = self._createClientRequirement(project.id, content)
            del response.headers['Content-Type']
            relative_url = h.url_for('clientrequirement', id=cr.id)
            response.headers['Location'] = self._getAbsoluteURL(relative_url)
            response.status_code = 201
            return
        except sqlalchemy.exceptions.InvalidRequestError:
            abort(400)

    def new(self, format='html'):
        """GET /clientrequirements/new: Form to create a new item."""
        # url_for('new_clientrequirement')
        c.url = h.url_for('clientrequirements')
        c.server = config['server.url']
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/clientrequirements/form.mako')

    def newByProject(self, project):
        c.project = project
        c.url = h.url_for('create_clientrequirements_by_project', project=project)
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return render('/clientrequirements/form.mako')

    def update(self, id):
        """PUT /clientrequirements/id: Update an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(h.url_for('clientrequirement', id=ID),
        #           method='put')
        # url_for('clientrequirement', id=ID)
        try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            doc = etree.fromstring(content)
            cr = Session.query(ClientRequirement).get(id)
            name = None
            if cr:
                name = doc.xpath('/requirement/name')
                if name:
                    cr.name = name[0].text
                description = doc.xpath('/requirement/description')
                if description:
                    cr.description = description[0].text
                project_id = doc.xpath('/requirement/project')
                if project_id:
                    cr.project_id = project_id[0].text
                estimation = doc.xpath('/requirement/estimation')
                if estimation:
                    cr.estimation = estimation[0].text
                priority_id = doc.xpath('/requirement/priority')
                if priority_id:
                    cr.priority_id = priority_id[0].text
                status_id = doc.xpath('/requirement/status')
                if status_id:
                    cr.status_id = status_id[0].text
                impact_id = doc.xpath('/requirement/impact')
                if impact_id:
                    cr.impact_id = impact_id[0].text
                type_id = doc.xpath('/requirement/type')
                if type_id:
                    cr.type_id = type_id[0].text
                requested_by = doc.xpath('/requirement/requestedby')
                if requested_by:
                    cr.requested_by = requested_by[0].text
                assigned_to = doc.xpath('/requirement/assignedto')
                if assigned_to:
                    cr.assigned_to = assigned_to[0].text
                release = doc.xpath('/requirement/release')
                if release:
                    cr.release = release[0].text
                iteration = doc.xpath('/requirement/iteration')
                if iteration:
                    cr.iteration = iteration[0].text
                #Session.save(cr)
                Session.commit()
                #print "Despues: %s" % cr
                #del response.headers['Content-Type']
                #response.status_code = 204
                return
            else:
                abort(404)
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)

    def delete(self, id):
        """DELETE /clientrequirements/id: Delete an existing item."""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(h.url_for('clientrequirement', id=ID),
        #           method='delete')
        # url_for('clientrequirement', id=ID)
        cr = Session.query(ClientRequirement).get(id)
        if cr:
            Session.delete(cr)
            Session.commit()
        del response.headers['Content-Type']
        response.status_code = 204
        return


    def show(self, id, format='html'):
        """GET /clientrequirements/id: Show a specific item."""
        # url_for('clientrequirement', id=ID)
        c.requirement = Session.query(ClientRequirement).get(id)
        if c.requirement:
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return render('/clientrequirements/view.mako')
        else:
            abort(404)

    def edit(self, id, format='html'):
        """GET /clientrequirements/id;edit: Form to edit an existing item."""
        # url_for('edit_clientrequirement', id=ID)
        pass

    def _createClientRequirement(self, project_id, data):
        try:
            project = Session.query(Project).get(project_id)
            if project:
                doc = etree.fromstring(data.encode("utf8"))
                name = doc.xpath('/requirement/name')[0].text
                description = doc.xpath('/requirement/description')[0].text
                priority = doc.xpath('/requirement/priority')[0].text
                status = doc.xpath('/requirement/status')[0].text
                impact = doc.xpath('/requirement/impact')[0].text
                type = doc.xpath('/requirement/type')[0].text
                cr = ClientRequirement()
                release = iteration = requested_by = assigned_to = None
                requested_by = doc.xpath('/requirement/requestedby')
                if requested_by:
                    cr.requested_by = requested_by[0].text
                assigned_to = doc.xpath('/requirement/assignedto')
                if assigned_to:
                    cr.assigned_to = assigned_to[0].text
                estimation = doc.xpath('/requirement/estimation')
                if estimation:
                    cr.estimation = estimation[0].text
                release = doc.xpath('/requirement/release')
                if release:
                    cr.release = release[0].text
                iteration = doc.xpath('/requirement/iteration')
                if iteration:
                    cr.iteration = iteration[0].text
                #print "PARAMETROS: name:%s, description:%s, priority:%s, status:%s, type:%s, impact:%s" % (name, description, priority, status, type, impact)
                cr.name = name
                cr.description = description
                cr.priority_id = priority
                cr.status_id = status
                cr.impact_id = impact
                cr.type_id = type
                project.client_requirements.append(cr)
                #print 'hóla'.encode("utf8")
                Session.save(cr)
                Session.commit()
                return cr
        except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)


